/*
 * @lc app=leetcode.cn id=592 lang=typescript
 *
 * [592] 分数加减运算
 */

// @lc code=start

function isDigit(c: string): boolean {
  return c >= '0' && c <= '9';
}

function gcd(a: number, b: number): number {
  if (b === 0) return a;
  return gcd(b, a % b);
}

function fractionAddition(expression: string): string {
  const n = expression.length;
  // 分子
  let numerator = 0;
  // 分母
  let denominator = 1;
  // 从 0 开始遍历
  let idx = 0;

  while (idx < n) {
    // 数字的正负号
    let sign = 1;
    if (expression[idx] === '-' || expression[idx] === '+') {
      sign = expression[idx] === '-' ? -1 : 1;
      idx++;
    }
    // 读取分子
    let numerator1 = 0;
    while (idx < n && isDigit(expression[idx])) {
      numerator1 = numerator1 * 10 + Number(expression[idx]);
      idx++;
    }
    numerator1 = numerator1 * sign;
    // 跳过 /
    idx++;
    // 读取分母
    let denominator1 = 0;
    while (idx < n && isDigit(expression[idx])) {
      denominator1 = denominator1 * 10 + Number(expression[idx]);
      idx++;
    }
    // 累加结果
    numerator = numerator * denominator1 + numerator1 * denominator;
    denominator *= denominator1;
  }

  // 如果分子为0，直接返回
  if (numerator === 0) {
    return '0/1';
  }
  // 计算分子和分母的最大公约数
  const g = gcd(Math.abs(numerator), denominator);
  // 返回结果
  return `${numerator / g}/${denominator / g}`;
}
// @lc code=end
